﻿using System;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Optimization;

namespace SelfManagement.Mvc.Bundle
{
    public class CssRewriteUrlTransform : IItemTransform
    {
        internal static string RebaseUrlToAbsolute(string baseUrl, string url)
        {
            if (string.IsNullOrWhiteSpace(url) || string.IsNullOrWhiteSpace(baseUrl) || url.StartsWith("/", StringComparison.OrdinalIgnoreCase))
            {
                return url;
            }
            if (!baseUrl.EndsWith("/", StringComparison.OrdinalIgnoreCase))
            {
                baseUrl += "/";
            }
            return VirtualPathUtility.ToAbsolute(baseUrl + url);
        }

        internal static string ConvertUrlsToAbsolute(string baseUrl, string content)
        {
            if (string.IsNullOrWhiteSpace(content))
            {
                return content;
            }
            Regex regex = new Regex("url\\(['\"]?(?<url>[^)]+?)['\"]?\\)");
            return regex.Replace(content, (Match match) => "url(" + CssRewriteUrlTransform.RebaseUrlToAbsolute(baseUrl, match.Groups["url"].Value) + ")");
        }

        public string Process(string includedVirtualPath, string input)
        {
            if (includedVirtualPath == null)
            {
                throw new ArgumentNullException("includedVirtualPath");
            }
            string directory = VirtualPathUtility.GetDirectory(includedVirtualPath.Substring(1));
            return CssRewriteUrlTransform.ConvertUrlsToAbsolute(directory, input);
        }
    }
}
